home *** CD-ROM | disk | FTP | other *** search
/ CU Amiga Super CD-ROM 24 / CU Amiga Magazine's Super CD-ROM 24 (1998)(EMAP Images)(GB)(Track 1 of 2)[!][issue 1998-07].iso / CUCD / Programming / SWI / source / boot / bags.pl < prev    next >
Encoding:
Text File  |  1997-05-06  |  1.4 KB  |  64 lines

  1. /*  $Id: bags.pl,v 1.3 1997/05/06 09:59:50 jan Exp $
  2.  
  3.     Copyright (c) 1990 Jan Wielemaker. All rights reserved.
  4.     jan@swi.psy.uva.nl
  5.  
  6.     Purpose: findall, bagof and setof
  7. */
  8.  
  9. :- module($bags, [
  10.     findall/3, 
  11.     bagof/3, 
  12.     setof/3]).
  13.  
  14. :- module_transparent
  15.     findall/3, 
  16.     setof/3, 
  17.     bagof/3, 
  18.     assert_bag/2.
  19.  
  20. %    findall(-Var, +Goal, -Bag)
  21. %    Bag holds all alternatives for Var  in  Goal.   Bag  might  hold
  22. %    duplicates.   Equivalent  to bagof, using the existence operator
  23. %    (^) on all free variables of Goal.  Succeeds with Bag  =  []  if
  24. %    Goal fails immediately.
  25.  
  26. findall(Var, Goal, Bag) :-
  27.     assert_bag(v-Var, Goal),
  28.     collect_bags([], [v-VarBag]), !,
  29.     VarBag = Bag.
  30. findall(_, _, []).
  31.  
  32. %    setof(+Var, +Goal, -Set
  33. %    Equivalent to bagof/3, but sorts the resulting bag  and  removes
  34. %    duplicate answers.
  35.  
  36. setof(Var, Goal, Set) :-
  37.     bagof(Var, Goal, Bag), 
  38.     sort(Bag, Set).
  39.  
  40. %    bagof(+Var, +Goal, -Bag)
  41. %    Implements Clocksin and  Melish's  bagof/3  predicate.   Bag  is
  42. %    unified  with the alternatives of Var in Goal, Free variables of
  43. %    Goal are bound, unless asked not to with the existence  operator
  44. %    (^).
  45.  
  46. bagof(Gen, Goal, Bag) :-
  47.     $e_free_variables(Gen^Goal, Vars),
  48.     assert_bag(Vars-Gen, Goal), 
  49.     collect_bags([], Bags), 
  50.     member(Vars-Bag, Bags),
  51.     Bag \== [].
  52.  
  53. assert_bag(Templ, G) :-
  54.     $record_bag(-), 
  55.     G,
  56.         $record_bag(Templ), 
  57.     fail.
  58. assert_bag(_, _).
  59.  
  60. collect_bags(Sofar, Result) :-
  61.     $collect_bag(Vars, Bag), !,
  62.     collect_bags([Vars-Bag|Sofar], Result).
  63. collect_bags(L, L).
  64.